require 'digest/sha1'

class User < ActiveRecord::Base
  
  validates_presence_of     :name
  validates_presence_of     :email
  validates_uniqueness_of   :name

  def validate
    errors.add_to_base("Missing password") if password.blank?
  end

  def self.authenticate(name, clearpassword)
    #are there any users?
    if self.count == 0
      user = self.new
      user.name = "dummy"
      user.password = "dummy"
      clearpassword = "dummy"
      name = "dummy"
      user.save
    end
    user = self.find_by_name(name)
    #logger.info("Name: #{name}")
    if user
      expected_password = encrypted_password(clearpassword, user.salt)
      
      # debug info
      logger.info("user is found!")
      logger.info("Expected => " + expected_password)
      logger.info("Given => " + user.password)
      
      if user.password != expected_password
        user = nil
      else
        logger.info("password is valid!")
      end
    end
    user
  end
  
  def password
    create_new_salt if !self.salt
    User.encrypted_password(super, self.salt)
  end
  
  private
  
  def self.encrypted_password(clearpassword, salt)
    string_to_hash = clearpassword + "wibble" + salt  # 'wibble' makes it harder to guess
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
end

